package com.ikangtai.shecare.common.db.sync;

import android.content.Context;

import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.baseView.collectionList.CollectionBean;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.DatabaseHelper;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncCollectedArticleMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

/**
 * 有网络写操作(如add，update，delete网络后台数据库等)之前时进行sync! 因为读操作，都是读取本地sqlite，不进行网络读取！
 * <p/>
 * 切记在混淆文件里添加EventBus的@Subscriber函数
 * <p/>
 * if(hasNetWork()){
 * 1) sync_sqlite_table_with_Network();  —> 此步执行完之后再执行2)，由于2者为异步线程，所以需要用EventBus来同步1）2）的执行顺序。
 * 2) okhttp … {
 * onFailure(){ operation_local_sqlite_TABLE_NAME(…, 0) }
 * onResponse(){
 * a) errorCode { operation_local_sqlite_TABLE_NAME(…, 0) }
 * b) code = 200 { operation_local_sqlite_TABLE_NAME(…, 1) }
 * }
 * }
 * } else {
 * operation_local_sqlite_TABLE_NAME(…, 0);
 * // if needed, set data got from local sqlite to UI View for display
 * }
 * <p/>
 * <p/>
 * 上面的1)在具体的Activity或者Fragment可以具体为
 * SyncCollectedArticle syncCollectedArticle = new SyncCollectedArticle(this / getActivity(), syncCollectedArticleMsg);
 * syncCollectedArticle.syncCollectionWithNetwork(); //里面执行 EventBus.getDefault().post(syncCollectedArticleMsg);
 * <p/>
 * 上面的2)在具体的Activity或者Fragment可以具体为
 *
 * @Subscriber private void syncCollectedArticle(SyncCollectedArticleMsg syncCollectedArticleMsg){
 * updateCollectedArticle();
 * }
 * <p/>
 * // 这个是之前就写好的网络操作函数，不用动，直接调用即可。
 * public void updateCollectedArticle(){
 * okhttp … {
 * onFailure(){ operation_local_sqlite_TABLE_NAME(…, 0) }
 * onResponse(){
 * a) errorCode { operation_local_sqlite_TABLE_NAME(…, 0) }
 * b) code = 200 { operation_local_sqlite_TABLE_NAME(…, 1) }
 * }
 * }
 * }
 * <p/>
 * 上面的operation_local_sqlite_TABLE_NAME()为本地sqlite操作，0表示未同步，1表示已同步
 * <p/>
 * 此具体用法可以详见 ArticleAdapter.java的 ArticleCollectClickListener!
 */

public class SyncCollectedArticle {
    private Context context;
    private SyncCollectedArticleMsg syncCollectedArticleMsg;

    public SyncCollectedArticle(Context context, SyncCollectedArticleMsg syncCollectedArticleMsg) {
        this.context = context;
        this.syncCollectedArticleMsg = syncCollectedArticleMsg;
        EventBus.getDefault().register(this);
    }

    public void syncCollectionWithNetwork() {
        final DBManager dbManager = new DBManager(context);

        List<CollectionBean> collectionBeanList = dbManager.getUnSyncedCollectionArticles(App.userName);

        if (collectionBeanList == null || collectionBeanList.size() == 0) {
            EventBus.getDefault().post(syncCollectedArticleMsg);
        } else {
            try {
                OKHttpUtil okHttpClient = new OKHttpUtil(context);
                String appendUrl = "collection/addCollection.json";
                JSONArray collectionBeanJsonArray = new JSONArray();
                AppLog.i("syncCollectionWithNetwork is syncing ...! have " + collectionBeanList.size() + " records in total!");

                for (int i = 0; i < collectionBeanList.size(); i++) {
                    JSONObject collectionBeanJSONObject = new JSONObject();
                    collectionBeanJSONObject.put("collectionID", collectionBeanList.get(i).getCollectionID());
                    collectionBeanJSONObject.put("collectionName", collectionBeanList.get(i).getCollectionTitle());
                    collectionBeanJSONObject.put("collectionURL", String.valueOf(collectionBeanList.get(i).getArticleId()));
                    collectionBeanJSONObject.put("collectionFrom", 1);
                    collectionBeanJSONObject.put("collectionDate", collectionBeanList.get(i).getCollectionDate());
                    collectionBeanJSONObject.put("collectionDelete", collectionBeanList.get(i).getCollectionDelete());
                    collectionBeanJsonArray.put(collectionBeanJSONObject);
                }

                okHttpClient.add("authToken", App.authToken);
                okHttpClient.add("collections", collectionBeanJsonArray);

                okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        super.onFailure(request, e);
                        EventBus.getDefault().post(syncCollectedArticleMsg);
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        int respCode = 0;

                        try {
                            JSONObject respJSONObj = new JSONObject(response.body().string());
                            respCode = respJSONObj.getInt("code");

                            if (App.HTTP_RESP_OK == respCode){
                                dbManager.updateDBSyncFlag(DatabaseHelper.COLLECTION_TABLE_NAME, App.userName);
                                AppLog.i("syncCollectionWithNetwork onResponse success!");
                            } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                                OKHttpUtil.setNewToken();
                                syncCollectionWithNetwork();
                            } else {
                                AppLog.i("syncCollectionWithNetwork onResponse failed! respCode is:" + respCode);
                            }
                        } catch (JSONException e) {
                            AppLog.i("syncCollectionWithNetwork JSONException!");
                            e.printStackTrace();
                        }

                        if (respCode != App.HTTP_RESP_TOKEN_TIME_OUT)
                            EventBus.getDefault().post(syncCollectedArticleMsg);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
                EventBus.getDefault().post(syncCollectedArticleMsg);
            }
        }
    }
}